/*
 * @(#)JsonUtil.java 2012-4-20
 *
 * Copyright 2012 SH-BBMF,Inc. All rights reserved.
 */
package com.fruit.app.common.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author ZuoChangjun 2012-4-20
 */
public class JsonUtil {
	private static Log logger = LogFactory.getLog(JsonUtil.class);

	/**
	 * Map对象转化为JSON字符串
	 * 
	 * @param map
	 * @param resultCode
	 * @return
	 */
	public static String toJsonStr(Map<String,Object> resultMap) {
		if (resultMap == null) {
			return null;
		}
		return JSONObject.fromObject(resultMap).toString();
	}

	/**
	 * jsonStr转换为Bean类
	 * 
	 * @param jsonString
	 * @param beanCalss
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T toBean(String jsonStr, Class<T> beanCalss) {
		try {
			if (StringUtils.isBlank(jsonStr)) {
				return beanCalss.newInstance();
			}
			JSONObject jsonObject = JSONObject.fromObject(jsonStr);
			return  (T)JSONObject.toBean(jsonObject, beanCalss);
		} catch (Exception e) {
			logger.error("jsonStr to Bean error :" + e.getMessage());
			return null;
		}
	}

	/**
	 * HttpServletRequest转换为Bean类
	 * 
	 * @param request
	 * @param beanCalss
	 * @return
	 */
	public static <T> T toBean(HttpServletRequest request, Class<T> beanCalss) {	
		try {
			String jsonStr = getJsonStrFromRequest(request);
			if (StringUtils.isBlank(jsonStr)) {
				return beanCalss.newInstance();
			}
			return toBean(jsonStr, beanCalss);
		} catch (Exception e) {
			logger.error("getJsonStrFromRequest error :" + e.getMessage());
			return null;
		}
	}

	/**
	 * resquest对象转换为jsonStr
	 * 
	 * @param request
	 * @return
	 */
	public static String getJsonStrFromRequest(HttpServletRequest request) {
		DataInputStream in = null;
		try {
			request.setCharacterEncoding("utf-8");
			System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(10000));
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
			// String jsonStr = new String(br.readLine());
			String inputLine = null;
			StringBuffer sb = new StringBuffer();
			while ((inputLine = br.readLine()) != null) {
				sb.append(inputLine).append("\n");
			}
			if (StringUtils.isBlank(sb.toString())) {
				return null;
			} else {
				return new String(sb.toString());
			}
			//return jsonStr;
		} catch (Exception e) {
			logger.error("getJsonStrFromRequest error :" + e.getMessage());
			return null;
		} finally {
			IOUtils.closeQuietly(in);
		}
	}
}
